package cn.com.generaldata.os.action;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Pm;
import cn.com.generaldata.os.pojo.ReportAttach;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.service.common.AbstractPmService;
import cn.com.generaldata.os.service.impl.UnitService;
import cn.com.generaldata.os.service.intf.ReportServiceInterface;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UnitVO;
import cn.com.generaldata.os.vo.UserVO;

@InjectName
@Component
public class PmAction {
	private static final String PROPERTY_NOTICE_RESULT_SIZE = "notice.result.size";
	private static final String GLOBAL_CONF_PATH = "global_conf.properties";
	private static final int DEFAULT_RESULT_SIZE = 20;

	@Autowired
	@Qualifier("pmFactoryBean")
	private AbstractPmService pmService;

	@Autowired
	private ReportServiceInterface reportService;

	@Autowired
	private UnitService unitService;
	@Value("${serviceIp}")
	public String ip;
	@Value("${servicePort}")
	public String port;
	@Value("${serviceName}")
	public String serviceName;

	//2014-9-11
	@At("/monitor/pm")
	@Ok("jsp:/static/ocean/monitor/pmlist")
	public ResultVO<Pm> getPmList(HttpSession session, HttpServletRequest request, @Param("p") Integer pageNum) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String toUserId = voUser.getId();
		int curPage = 0;
		if (pageNum != null) {
			curPage = pageNum;
		} else {
			curPage = 1;
		}
		return pmService.getPmList(toUserId, curPage);
	}

	//2014-9-11
	@At("/monitor/pmdetail")
	@Ok("jsp:/static/ocean/monitor/detailpmlist")
	public void queryPmById(String id, HttpServletRequest request) {
		pmService.setPmRead(id);
		Pm pm = pmService.queryPmById(id);
		String attchs = pm.getFujian();
		String title = pm.getTitle();
		String content = pm.getContent();
		String pmFromName = pm.getPmFromName();
		request.setAttribute("id", id);
		request.setAttribute("title", title);
		request.setAttribute("content", content);
		request.setAttribute("pmFromName", pmFromName);
		//获取频率类型信息
		request.setAttribute("serviceIp", ip);
		//获取频率类型信息
		request.setAttribute("servicePort", port);
		request.setAttribute("serviceName", serviceName);
		List<ReportAttach> AttchList = new ArrayList<ReportAttach>();
		if (attchs != null) {
			String[] fjs = attchs.split(",");
			for (String attch : fjs) {
				if (attch.trim().length() == 0) {
					continue;
				}

				AttchList.add(reportService.queryReportAttachById(attch));
			}
		}
		request.setAttribute("AttchList", AttchList);
	}

	//
	@At("/monitor/pmreply")
	@Ok("jsp:/static/ocean/monitor/pmreply")
	public Pm queryPmByIdRly(String id) {
		return pmService.queryPmById(id);
	}

	//
	@At("/monitor/sendMes")
	@Ok("jsp:/static/ocean/monitor/sendmes")
	public void popSend() {

	}

	//
	@At("/monitor/selRec")
	@Ok("jsp:/static/ocean/monitor/selectrec")
	public List<UnitVO> queryCompanyByName(HttpSession session, HttpServletRequest request,
			@Param("recIds") String recIds, @Param("cName") String cName) {
		Pm pm = pmService.queryPmById(recIds);
		String pName = "";
		String pId = "";
		if (pm != null) {
			pName = pm.getPmFromName();
			pId = pm.getPmFrom();
		}

		request.setAttribute("recNames", pName);
		request.setAttribute("recIds", pId);
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String toUserId = voUser.getId();
		List<Unit> list = pmService.queryCompanyByName(cName, toUserId);
		return toVoResult(list);
	}

	@SuppressWarnings("unchecked")
	private List<UnitVO> toVoResult(List<cn.com.generaldata.os.pojo.Unit> list) {
		List<UnitVO> units = new ArrayList<UnitVO>();
		for (cn.com.generaldata.os.pojo.Unit pUnit : list) {
			units.add(toVo(pUnit));
		}

		return units;
	}

	private UnitVO toVo(cn.com.generaldata.os.pojo.Unit pUnit) {
		if (pUnit != null) {
			String roleId = pUnit.getRole() == null ? null : pUnit.getRole().getId();
			String roleName = pUnit.getRole() == null ? null : pUnit.getRole().getRoleName();
			// String industryId = pUnit.getIndustryId() == null ? null : pUnit.getIndustry().getId();
			String industryName = null;
			String areaId = pUnit.getArea() == null ? null : pUnit.getArea().getId();
			String areaName = pUnit.getArea() == null ? null : pUnit.getArea().getAreaName();
			String lareaId = pUnit.getLarea() == null ? null : pUnit.getLarea().getId();
			String lareaName = pUnit.getLarea() == null ? null : pUnit.getLarea().getLareaName();
			String registAreaId = pUnit.getRegistArea() == null ? null : pUnit.getRegistArea().getId();
			String registAreaName = pUnit.getRegistArea() == null ? null : pUnit.getRegistArea().getAreaName();
			String registLAreaId = pUnit.getRegistLArea() == null ? null : pUnit.getRegistLArea().getId();
			String registLAreaName = pUnit.getRegistLArea() == null ? null : pUnit.getRegistLArea().getLareaName();
			List<String> users = new ArrayList<String>();
			if (pUnit.getUsers() != null) {
				for (cn.com.generaldata.os.pojo.User user : pUnit.getUsers()) {
					users.add(user.getId());
				}
			}
			String unitProperName = "";
			if (pUnit.getUnitProper() != null) {
				if (pUnit.getUnitProper().indexOf("1") != -1) {
					unitProperName = "涉海企业";
				} else if (pUnit.getUnitProper().indexOf("2") != -1) {
					unitProperName = "用海企业";
				} else if (pUnit.getUnitProper().indexOf("3") != -1) {
					unitProperName = "开发区企业";
				}
			}
			return new UnitVO(pUnit.getId(), roleId, roleName, pUnit.getIndustryId(), industryName, areaId, areaName,
					lareaId, lareaName, pUnit.getUnitName(), pUnit.getUnitInstitutionName(),
					pUnit.getUnitInstitutionCode(), pUnit.getRegistAdd(), pUnit.getAddr(), registAreaId,
					registAreaName, registLAreaId, registLAreaName, pUnit.getQh(), pUnit.getTel(), pUnit.getFax(),
					pUnit.getMobile(), pUnit.getZclx(), pUnit.getLsgx(), pUnit.getDl(), pUnit.getZl(), pUnit.getXl(),
					pUnit.getLm(), pUnit.getYyzt(), pUnit.getProduct1(), pUnit.getProduct2(), pUnit.getProduct3(),
					pUnit.getKgqk(), pUnit.getPractitioner(), pUnit.getQyjt(), pUnit.getSuperCompanyCode(),
					pUnit.getFr(), pUnit.getUnitProper(), unitProperName, pUnit.getCreateYear(), users,
					pUnit.getProInfo(), pUnit.getKkx(), pUnit.getKky(), pUnit.getKkz(), pUnit.getDlx(), pUnit.getDly(),
					pUnit.getDlz(), pUnit.getPid());
		}
		return null;
	}

	//
	@At("/monitor/sendFi")
	@POST
	@Ok("jsp:/static/ocean/monitor/sendmes")
	@AdaptBy(type = UploadAdaptor.class)
	public void sendPm(HttpSession session, HttpServletRequest request, @Param("recids") String recids,
			@Param("title") String title, @Param("content") String content, @Param("picFile1") TempFile picFile1,
			@Param("picFile2") TempFile picFile2, @Param("picFile3") TempFile picFile3,
			@Param("picFile4") TempFile picFile4, @Param("picFile5") TempFile picFile5, ServletContext context) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String fromUserId = voUser.getId();

		//String folderPath = context.getRealPath("/") + "upload/";
		//String folderPath = "D:/upload/";

		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			System.out.print(ex);
		}
		String folderPath = properties.getProperty("fileUploadPath").trim();

		String fj = "";
		String s1 = saveFile(picFile1, folderPath, voUser);
		String s2 = saveFile(picFile2, folderPath, voUser);
		String s3 = saveFile(picFile3, folderPath, voUser);
		String s4 = saveFile(picFile4, folderPath, voUser);
		String s5 = saveFile(picFile5, folderPath, voUser);

		if (!"".equals(s1)) {
			fj = fj + s1 + ",";
		}
		if (!"".equals(s2)) {
			fj = fj + s2 + ",";
		}
		if (!"".equals(s3)) {
			fj = fj + s3 + ",";
		}
		if (!"".equals(s4)) {
			fj = fj + s4 + ",";
		}
		if (!"".equals(s5)) {
			fj = fj + s5 + ",";
		}

		pmService.sendPm(fromUserId, recids, title, content, fj);

		request.setAttribute("result", "success");
	}

	private String saveFile(TempFile picFile, String folderPath, UserVO voUser) {
		if (picFile != null) {
			String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String fileName = picFile.getMeta().getFileLocalName();
			String ext = picFile.getMeta().getFileExtension();
			String newFileName = voUser.getId() + timeStr + ext;
			moveFile(picFile.getFile(), folderPath + newFileName);

			ReportAttach reportAttach = new ReportAttach();
			reportAttach.setAttachFilename(fileName);
			reportAttach.setUserId(voUser.getId());
			reportAttach.setUserUnit(unitService.queryUnitById(voUser.getUserUnitId()).getUnitName());
			reportAttach.setSysCreateDate(new Date());
			reportAttach.setIsDisposal(3);// 通知中的附件
			reportAttach.setAttachPathname(newFileName);
			reportAttach.setAttachExplain("");

			return reportService.addReportAttachments(reportAttach);

		} else
			return "";
	}

	private boolean moveFile(File source, String target) {

		if (source == null || target == null || "".equals(target)) {
			return false;
		}

		int dot = target.lastIndexOf(source.separator);
		String floder = target.substring(0, dot);
		File fl = new File(floder);
		if (!fl.exists()) {
			fl.mkdirs();
		}

		File f = new File(target);

		if (!f.exists()) {
			return source.renameTo(f);
		}

		return false;
	}

	public void setPmRead(String pmId) {
		pmService.setPmRead(pmId);
	}

	private int getDefaultResultSize() {
		ClassPathResource resource = new ClassPathResource(GLOBAL_CONF_PATH);
		int resultSize = DEFAULT_RESULT_SIZE;

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(resource.getFile().getAbsolutePath());

			Properties properties = new Properties();
			properties.load(fis);

			String str = properties.getProperty(PROPERTY_NOTICE_RESULT_SIZE, "");
			if (StringUtils.isNotBlank(str)) {
				return Integer.valueOf(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (Exception e) {
			}
		}
		return resultSize;
	}

	// 自加

	public boolean existUnReadPms(String userId) {
		Page page = new Page(1, getDefaultResultSize());
		return pmService.existUnReadPms(userId, page);
	}

	public int countCompanyByName(String name, String role) {
		return pmService.countCompanyByName(name, role);
	}

	public List<Pm> getAllPmList(String toUserId) {
		return pmService.getAllPmList(toUserId);
	}

}
